import 'package:city_pickers/city_pickers.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import 'package:multi_dropdown/multi_dropdown.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/views/home/model/customer_tag.dart';
import 'package:yuan_hang_app/views/home/model/leads_follow_info.dart';
import 'package:yuan_hang_app/views/home/model/leads_follow_rule.dart';
import 'package:yuan_hang_app/views/home/model/leads_history.dart';
import 'package:yuan_hang_app/views/home/view/leads/widget/common_date.dart';
import 'package:yuan_hang_app/views/home/view/leads/widget/leads_call_log_list.dart';
import 'package:yuan_hang_app/views/home/view/leads/widget/leads_history_list.dart';
import 'package:yuan_hang_app/views/home/view/order/order_edit_page.dart';
import 'package:yuan_hang_app/widget/common_attachment.dart';
import 'package:yuan_hang_app/widget/label_item.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

import '../../../../base/base_page.dart';
import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_colors.dart';
import '../../../../res/w_dimens.dart';
import '../../../../widget/custom_tab.dart';
import '../../../../widget/status_btn.dart';
import '../../../../widget/w_popup_window.dart';
import '../../../../widget/w_text.dart';
import '../../model/leads.dart';
import '../../model/leads_call_log.dart';

class LeadsFollowUpDetailPage extends StatefulWidget {
  final int clueId;

  const LeadsFollowUpDetailPage({super.key, required this.clueId});

  @override
  BaseState<LeadsFollowUpDetailPage> createState() =>
      _LeadsFollowUpDetailPageState();
}

class _LeadsFollowUpDetailPageState extends BaseState<LeadsFollowUpDetailPage> {
  List<Map> tabList = [
    {"title": "基本信息"},
    {"title": "客户跟进"},
    {"title": "接触历史"},
    {"title": "通话记录"}
  ];

  int selectedTabIndex = 0;
  int dayLimit = 7;

  Leads leadsInfo = Leads();
  List<LeadsHistory> leadsHistoryList = [];
  List<LeadsCallLog> leadsCallLogList = [];
  LeadsFollowInfo leadsFollowInfo = LeadsFollowInfo();
  List<LeadsFollowRule> leadsFollowRule = [];
  late ScrollController _scrollController;

  List<Map> activityList = [];
  List<DropdownItem<CustomerTag>> items = [];
  List<DropdownItem<CustomerTag>> selectedItems = [];
  final MultiSelectController<CustomerTag> _controller =
      MultiSelectController();

  List picList = [];
  List picUrlList = [];
  List? timeSlots = [];
  List? filterTimeSlots = [];

  Status historyListStatus = Status.NONE;
  Status callLogListStatus = Status.NONE;

  GlobalKey<LabelItemState>? customerNameKey;
  GlobalKey<LabelItemState>? sexKey;
  GlobalKey<LabelItemState>? wechatKey;
  GlobalKey<LabelItemState>? customerTypeKey;
  GlobalKey<LabelItemState>? companyNameKey;
  GlobalKey<LabelItemState>? levelKey;
  GlobalKey<LabelItemState>? modelKey;
  GlobalKey<LabelItemState>? leadsSourceKey;
  GlobalKey<LabelItemState>? activityKey;
  GlobalKey<LabelItemState>? idTypeKey;
  GlobalKey<LabelItemState>? idNoKey;
  GlobalKey<LabelItemState>? areaKey;
  GlobalKey<LabelItemState>? addressKey;
  GlobalKey<LabelItemState>? purchaseDateKey;
  GlobalKey<LabelItemState>? isSubstitutionKey;
  GlobalKey<LabelItemState>? isLoanKey;
  GlobalKey<LabelItemState>? budgetKey;
  GlobalKey<LabelItemState>? birthdayKey;
  GlobalKey<LabelItemState>? ageKey;
  GlobalKey<LabelItemState>? emailKey;
  GlobalKey<LabelItemState>? customerTagKey;
  GlobalKey<LabelItemState>? remarkKey;
  GlobalKey<CommonAttachmentState>? picKey;

  GlobalKey<LabelItemState>? invalidReasonKey;
  GlobalKey<LabelItemState>? defeatReasonKey;
  GlobalKey<LabelItemState>? nextFollowTimeKey;
  GlobalKey<LabelItemState>? appointDriveTimeKey;
  GlobalKey<LabelItemState>? appointDriveTimeShowKey;
  Map<String, dynamic> cityData = {"provincesData": [], "citiesData": []};
  String areaStr = "";

  List<Map> _attachmentImages = [];

  @override
  void initState() {
    super.initState();

    ///线索信息需要刷新的key
    customerNameKey = GlobalKey(debugLabel: "customerNameKey");
    sexKey = GlobalKey(debugLabel: "sexKey");
    wechatKey = GlobalKey(debugLabel: "wechatKey");
    customerTypeKey = GlobalKey(debugLabel: "customerTypeKey");
    companyNameKey = GlobalKey(debugLabel: "companyNameKey");
    levelKey = GlobalKey(debugLabel: "levelKey");
    modelKey = GlobalKey(debugLabel: "modelKey");
    leadsSourceKey = GlobalKey(debugLabel: "leadsSourceKey");
    activityKey = GlobalKey(debugLabel: "activityKey");
    idTypeKey = GlobalKey(debugLabel: "idTypeKey");
    idNoKey = GlobalKey(debugLabel: "idNoKey");
    areaKey = GlobalKey(debugLabel: "areaKey");
    addressKey = GlobalKey(debugLabel: "addressKey");
    purchaseDateKey = GlobalKey(debugLabel: "purchaseDateKey");
    isSubstitutionKey = GlobalKey(debugLabel: "isSubstitutionKey");
    isLoanKey = GlobalKey(debugLabel: "isLoanKey");
    budgetKey = GlobalKey(debugLabel: "budgetKey");
    birthdayKey = GlobalKey(debugLabel: "birthdayKey");
    ageKey = GlobalKey(debugLabel: "ageKey");
    emailKey = GlobalKey(debugLabel: "emailKey");
    customerTagKey = GlobalKey(debugLabel: "customerTagKey");
    remarkKey = GlobalKey(debugLabel: "remarkKey");
    picKey = GlobalKey(debugLabel: "picKey");

    ///客户跟进需要刷新的key
    invalidReasonKey = GlobalKey(debugLabel: "invalidReasonKey");
    defeatReasonKey = GlobalKey(debugLabel: "defeatReasonKey");
    nextFollowTimeKey = GlobalKey(debugLabel: "nextFollowTimeKey");
    appointDriveTimeKey = GlobalKey(debugLabel: "appointDriveTimeKey");
    appointDriveTimeShowKey = GlobalKey(debugLabel: "appointDriveTimeShowKey");
    fetchLeadsInfo(widget.clueId);
    fetchHistoryList(widget.clueId);
    fetchCallLogList(widget.clueId);
    getCityList();
    fetchFollowRule();
    fetchCustomerTagList();
    fetchActivityList();
    getTimeSlot();

    leadsFollowInfo.clueId = widget.clueId;


    _scrollController = ScrollController();
    // _scrollController.addListener(() {
    //   if (_scrollController.position.pixels >=
    //       _scrollController.position.maxScrollExtent / 2) {
    //     String areaStr =
    //         "${leadsInfo.provinceName}${leadsInfo.cityName}${leadsInfo.countyName}";
    //     areaKey!.currentState
    //         ?.refreshCity(leadsInfo.city.toString() ?? "", areaStr);
    //     birthdayKey!.currentState?.refreshDate(leadsInfo.birthday);
    //     picKey!.currentState?.refreshImageList(_attachmentImages);
    //   }
    // });
  }

  void getCityList() {
    HttpUtils().get(Api.getRegionList2).then((value) {
      if (value.resultCode == 200) {
        cityData = value.data;
        setState(() {});
      }
    });
  }

  void getTimeSlot() {
    ///新增预约的时候加载排版数据
    HttpUtils()
        .get("${Api.getTestDriveTimeList}/${WConstant().userInfo.shopId}")
        .then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        timeSlots = data.data;
        setState(() {});
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  ///获取客户标签
  fetchCustomerTagList() {
    CommonReqUtils.getTagList().then((list) {
      setState(() {
        items = (list ?? [])
            .map((item) => DropdownItem(
                label: item["tagName"],
                value: CustomerTag(
                    id: int.parse(item["id"].toString()),
                    tagName: item["tagName"])))
            .toList();
        if (items.isNotEmpty && selectedItems.isNotEmpty) {
          for (int i = 0; i < items.length; i++) {
            DropdownItem<CustomerTag> item = items[i];
            for (int j = 0; j < selectedItems.length; j++) {
              DropdownItem<CustomerTag> selectedItem = selectedItems[j];
              if (item.value.id == selectedItem.value.id) {
                item.selected = true;
              }
            }
          }
          _controller.setItems(items);
        }
      });
    });
  }

  ///获取活动列表
  fetchActivityList() {
    showLoading();
    HttpUtils().get(Api.getActivityList).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        List data = value.data;
        if (data.isNotEmpty) {
          for (int i = 0; i < data.length; i++) {
            Map item = {
              "label": data[i]["activityName"],
              "value": data[i]["id"]
            };
            activityList.add(item);
          }
        }
      } else {
        Toast.toast(value.errMsg);
      }
    });
  }

  ///获取线索跟进规则
  fetchFollowRule() {
    showLoading();
    HttpUtils().get(Api.getFollowRule).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          List data = value.data;
          if (data.isNotEmpty) {
            for (int i = 0; i < data.length; i++) {
              leadsFollowRule.add(LeadsFollowRule.fromJson(data[i]));
            }
          }
        }
      } else {
        Toast.toast(value.errMsg);
      }
    });
  }

  ///获取线索详情
  fetchLeadsInfo(int clueId) {
    showLoading();
    HttpUtils().get("${Api.getClueDetail}/${clueId}").then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          leadsInfo = Leads.fromJson(value.data);
          areaStr =
              "${leadsInfo.provinceName}${leadsInfo.cityName}${leadsInfo.countyName}";

          customerNameKey!.currentState
              ?.refreshInput(leadsInfo.customerName ?? "");
          sexKey!.currentState
              ?.refreshList(WConstant.sexList, leadsInfo.sex.toString());
          wechatKey!.currentState?.refreshInput(leadsInfo.wechat ?? "");
          customerTypeKey!.currentState?.refreshList(
              WConstant.customerTypeList, leadsInfo.customerType.toString());
          companyNameKey!.currentState
              ?.refreshInput(leadsInfo.companyName ?? "");
          levelKey!.currentState?.refreshList(
              WConstant.intentRangeList, leadsInfo.level.toString());
          modelKey!.currentState?.refreshList(
              CommonReqUtils.getLabelListByKey(CommonReqUtils.carType),
              leadsInfo.modelId);
          leadsSourceKey!.currentState?.refreshList(
              WConstant.leaderSourceLst, leadsInfo.clueSource.toString());
          idTypeKey!.currentState?.refreshList(
              WConstant.cardTypeList, leadsInfo.idType.toString());
          idNoKey!.currentState?.refreshInput(leadsInfo.idNo ?? "");
          areaKey!.currentState
              ?.refreshCity(leadsInfo.city.toString() ?? "", areaStr);
          addressKey!.currentState?.refreshInput(leadsInfo.address ?? "");
          purchaseDateKey!.currentState?.refreshDate(leadsInfo.purchaseDate);
          isSubstitutionKey!.currentState?.refreshList(
              WConstant.yesOrNoList, leadsInfo.isSubstitution.toString());
          isLoanKey!.currentState
              ?.refreshList(WConstant.yesOrNoList, leadsInfo.isLoan.toString());
          budgetKey!.currentState
              ?.refreshInput(leadsInfo.budgetAmount.toString() ?? "");
          birthdayKey!.currentState?.refreshDate(leadsInfo.birthday);
          ageKey!.currentState?.refreshInput(
              leadsInfo.age == null ? "" : leadsInfo.age.toString());
          emailKey!.currentState?.refreshInput(leadsInfo.eMail ?? "");
          remarkKey!.currentState?.refreshInput(leadsInfo.remark ?? "");
          picList = (leadsInfo.filesList ?? [])
              .map((item) => item["fileUploadInfoId"])
              .toList();
          picUrlList =
              (leadsInfo.filesList ?? []).map((item) => item["url"]).toList();
          picKey!.currentState?.refreshList(picUrlList);
          selectedItems = (leadsInfo.appCustomerTagList ?? [])
              .map((item) => DropdownItem(
                  label: item["tagName"],
                  value: CustomerTag(
                      id: int.parse(item["id"].toString()),
                      tagName: item["tagName"])))
              .toList();
          leadsFollowInfo.modelId = leadsInfo.modelId;
          setState(() {});
          if (items.isNotEmpty && selectedItems.isNotEmpty) {
            for (int i = 0; i < items.length; i++) {
              DropdownItem<CustomerTag> item = items[i];
              for (int j = 0; j < selectedItems.length; j++) {
                DropdownItem<CustomerTag> selectedItem = selectedItems[j];
                if (item.value.id == selectedItem.value.id) {
                  item.selected = true;
                }
              }
            }
            _controller.setItems(items);
          }
        }
      } else {
        Toast.toast(value.errMsg);
      }
    });
  }

  ///获取线索接触历史
  fetchHistoryList(int clueId) {
    showLoading();
    HttpUtils().get("${Api.getContactList}/${clueId}").then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          List data = value.data;
          if (data.isNotEmpty) {
            for (int i = 0; i < data.length; i++) {
              leadsHistoryList.add(LeadsHistory.fromJson(data[i]));
            }
          } else {
            historyListStatus = Status.EMPTY;
          }
        }
      } else {
        historyListStatus = Status.ERROR;
      }
    });
  }

  ///获取通话记录
  fetchCallLogList(int clueId) {
    showLoading();
    HttpUtils().get("${Api.getPhoneList}/${clueId}").then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          List data = value.data;
          if (data.isNotEmpty) {
            for (int i = 0; i < data.length; i++) {
              leadsCallLogList.add(LeadsCallLog.fromJson(data[i]));
            }
          } else {
            callLogListStatus = Status.EMPTY;
          }
        }
      } else {
        callLogListStatus = Status.ERROR;
      }
    });
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "线索跟进记录编辑",
        resizeToBottomInset: true,
        rightWidget: _rightWidget(selectedTabIndex),
        child: Column(
          children: [
            CustomTab(
              tabList: tabList,
              tabClick: (index) {
                setState(() {
                  selectedTabIndex = index;
                });
              },
            ),
            Expanded(child: _renderTabByIndex(selectedTabIndex))
          ],
        ));
  }

  _rightWidget(index) {
    if (index == 0) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          GestureDetector(
            onTap: () {
              CommonUtils.throttle(updateClueInfo);
            },
            child: WText(
              "保存",
              style: TextStyle(
                color: WColors.primaryColor,
                fontSize: 14.px,
              ),
            ),
          ),
          SizedBox(
            width: 10.px,
          ),
          //暂时不上订单模块
          // GestureDetector(
          //   onTap: () {
          //     RouteHelper.pushWidget(context, OrderEditPage(clueInfo: leadsInfo,));
          //   },
          //   child: WText(
          //     "转订单",
          //     style: TextStyle(
          //       color: WColors.primaryColor,
          //       fontSize: 14.px,
          //     ),
          //   ),
          // )
        ],
      );
    } else if (index == 1) {
      return GestureDetector(
        onTap: () {
          CommonUtils.throttle(saveFollowUpInfo);
        },
        child: WText(
          "跟进保存",
          style: TextStyle(
            color: WColors.primaryColor,
            fontSize: 14.px,
          ),
        ),
      );
    }
  }

  updateClueInfo() {
    if (Leads.check(leadsInfo)) {
      showLoading();
      HttpUtils().post(Api.updateClue, data: leadsInfo.toJson()).then((value) {
        hideLoading();
        if (value.resultCode == 200) {
          Toast.toast("保存成功");
        } else {
          Toast.toast(value.errMsg);
        }
      });
    }
  }

  saveFollowUpInfo() {
    if (LeadsFollowInfo.check(leadsFollowInfo, false)) {
      showLoading();
      HttpUtils()
          .post(Api.saveFollowInfo, data: leadsFollowInfo.toJson())
          .then((value) {
        hideLoading();
        if (value.resultCode == 200) {
          Toast.toast("保存成功");
          RouteHelper.maybePop(context, true);
        } else {
          Toast.toast("${value.errMsg}");
        }
      });
    }
  }

  Widget _renderTabByIndex(index) {
    if (index == 0) {
      return _baseInfoList();
    } else if (index == 1) {
      return _followUpList();
    } else if (index == 2) {
      return LeadsHistoryList(
        historyList: leadsHistoryList,
        status: historyListStatus,
      );
    } else {
      return LeadsCallLogList(
        logList: leadsCallLogList,
        status: callLogListStatus,
      );
    }
  }

  Widget _baseInfoList() {
    return ListView(
      controller: _scrollController,
      padding: EdgeInsets.zero,
      children: [
        LabelItem(
          key: customerNameKey,
          label: "客户名称",
          maxLength: 50,
          value: leadsInfo.customerName,
          labelType: LabelType.INPUT,
          onChanged: (text) {
            setState(() {
              leadsInfo.customerName = text;
            });
          },
        ),
        LabelItem(
          label: "性别",
          labelType: LabelType.LIST,
          key: sexKey,
          onSelected: (value) {
            setState(() {
              leadsInfo.sex = value == null ? null : int.parse(value);
            });
          },
          dataList: WConstant.sexList,
          value: leadsInfo.sex.toString(),
        ),
        LabelItem(
          label: "手机号码",
          value: leadsInfo.phone,
          isEnabled: false,
        ),
        LabelItem(
          key: wechatKey,
          label: "微信号",
          maxLength: 30,
          value: leadsInfo.wechat,
          labelType: LabelType.INPUT,
          onChanged: (text) {
            setState(() {
              leadsInfo.wechat = text;
            });
          },
        ),
        LabelItem(
          key: customerTypeKey,
          label: "客户类型",
          labelType: LabelType.LIST,
          onSelected: (value) {
            setState(() {
              leadsInfo.customerType = value == null ? null : int.parse(value);
            });
          },
          dataList: WConstant.customerTypeList,
          value: leadsInfo.customerType.toString(),
        ),
        LabelItem(
          key: companyNameKey,
          label: "公司名称",
          maxLength: 50,
          value: leadsInfo.companyName,
          labelType: LabelType.INPUT,
          onChanged: (text) {
            setState(() {
              leadsInfo.companyName = text;
            });
          },
        ),
        LabelItem(
          label: "意向级别",
          value: CommonReqUtils.exchangeCodeToName(
              CommonReqUtils.intentRange, leadsInfo.level),
          isEnabled: false,
        ),
        LabelItem(
          key: modelKey,
          label: "意向车型",
          labelType: LabelType.DROW_DOWN,
          onSelected: (value) {
            setState(() {
              leadsInfo.modelId = value;
            });
          },
          dataList: CommonReqUtils.getLabelListByKey(CommonReqUtils.carType),
          value: leadsInfo.modelId.toString(),
        ),
        LabelItem(
          label: "线索来源",
          value: CommonReqUtils.exchangeCodeToName(
              CommonReqUtils.leaderSource, leadsInfo.clueSource),
          isEnabled: false,
        ),
        LabelItem(
          label: "市场活动",
          value: leadsInfo.activityName,
          isEnabled: false,
        ),
        LabelItem(
          key: idTypeKey,
          label: "证件类型",
          labelType: LabelType.DROW_DOWN,
          onSelected: (value) {
            setState(() {
              leadsInfo.idType = value == null ? null : int.parse(value);
            });
          },
          dataList: WConstant.cardTypeList,
          value: leadsInfo.idType.toString(),
        ),
        LabelItem(
          key: idNoKey,
          label: "证件号码",
          maxLength: 50,
          value: leadsInfo.idNo,
          labelType: LabelType.INPUT,
          onChanged: (text) {
            setState(() {
              leadsInfo.idNo = text;
            });
          },
        ),
        getCityLabel(),
        LabelItem(
          key: addressKey,
          label: "详细地址",
          maxLength: 50,
          value: leadsInfo.address,
          labelType: LabelType.INPUT,
          onChanged: (text) {
            setState(() {
              leadsInfo.address = text;
            });
          },
        ),
        LabelItem(
          key: leadsSourceKey,
          label: "线索状态",
          value: CommonReqUtils.exchangeCodeToName(
              CommonReqUtils.leadsStatus, leadsInfo.status),
          isEnabled: false,
        ),
        LabelItem(
          label: "直营店",
          value: leadsInfo.shopName,
          isEnabled: false,
        ),
        LabelItem(
          label: "销售顾问",
          value: leadsInfo.salemanName,
          isEnabled: false,
        ),
        LabelItem(
          label: "线索创建时间",
          value: leadsInfo.createdAt,
          isEnabled: false,
        ),
        LabelItem(
          label: "线索下发时间",
          value: leadsInfo.distributeDate,
          isEnabled: false,
        ),
        getIntentDate(),
        // LabelItem(
        //   key: purchaseDateKey,
        //   labelType: LabelType.DATE,
        //   minDateTime: DateTime.now(),
        //   label: "意向购车日期",
        //   onDateChanged: (text) {
        //     setState(() {
        //       leadsInfo.purchaseDate = text;
        //     });
        //   },
        //   selectedDate: leadsInfo.purchaseDate,
        // ),
        LabelItem(
          key: isSubstitutionKey,
          label: "是否置换",
          labelType: LabelType.LIST,
          onSelected: (value) {
            setState(() {
              leadsInfo.isSubstitution =
                  value == null ? null : int.parse(value);
            });
          },
          dataList: WConstant.yesOrNoList,
          value: leadsInfo.isSubstitution.toString(),
        ),
        LabelItem(
          key: isLoanKey,
          label: "是否需要贷款",
          labelType: LabelType.LIST,
          onSelected: (value) {
            setState(() {
              leadsInfo.isLoan = value == null ? null : int.parse(value);
            });
          },
          dataList: WConstant.yesOrNoList,
          value: leadsInfo.isLoan.toString(),
        ),
        LabelItem(
          key: budgetKey,
          label: "购车预算",
          maxLength: 50,
          value: leadsInfo.budgetAmount,
          labelType: LabelType.INPUT,
          onChanged: (text) {
            setState(() {
              leadsInfo.budgetAmount = text;
            });
          },
        ),
        getBirthday(),
        // LabelItem(
        //   key: birthdayKey,
        //   labelType: LabelType.DATE,
        //   minDateTime: DateTime(1970, 1, 1),
        //   label: "客户生日",
        //   onDateChanged: (text) {
        //     setState(() {
        //       leadsInfo.birthday = text;
        //     });
        //   },
        //   selectedDate: leadsInfo.birthday,
        // ),
        LabelItem(
          labelType: LabelType.INPUT,
          label: "年龄",
          maxLength: 3,
          onChanged: (text) {
            leadsInfo.age = text;
          },
          value: leadsInfo.age,
        ),
        LabelItem(
          key: emailKey,
          label: "电子邮箱",
          maxLength: 50,
          value: leadsInfo.eMail,
          labelType: LabelType.INPUT,
          onChanged: (text) {
            setState(() {
              leadsInfo.eMail = text;
            });
          },
        ),
        const LabelItem(
          label: "客户标签",
          value: "",
          isLast: true,
        ),
        Container(
          decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                bottom: BorderSide(
                  color: WColors.border, // 边框颜色
                  width: 0.5.px, // 边框宽度
                ),
              )),
          child: MultiDropdown<CustomerTag>(
            items: items,
            controller: _controller,
            enabled: true,
            chipDecoration: ChipDecoration(
              labelStyle:
                  TextStyle(color: WColors.white, fontSize: WDimens.tsLabel),
              backgroundColor: WColors.primaryColor,
              wrap: true,
              runSpacing: 2,
              spacing: 10,
            ),
            fieldDecoration: FieldDecoration(
              hintText: '请选择',
              hintStyle: TextStyle(
                  color: WColors.hintTextColor, fontSize: WDimens.tsLabel),
              showClearIcon: true,
              border: const OutlineInputBorder(
                  borderSide: BorderSide(width: 0, color: Colors.transparent)),
              focusedBorder: const OutlineInputBorder(
                  borderSide: BorderSide(width: 0, color: Colors.transparent)),
            ),
            dropdownDecoration: const DropdownDecoration(
              maxHeight: 500,
            ),
            dropdownItemDecoration: DropdownItemDecoration(
              selectedIcon:
                  const Icon(Icons.check_box, color: WColors.primaryColor),
              disabledIcon: Icon(Icons.lock, color: Colors.grey.shade300),
            ),
            onSelectionChange: (selectedItems) {
              leadsInfo.appCustomerTagList = selectedItems
                  .map((item) => {"tagName": item.tagName, "id": item.id})
                  .toList();
            },
          ),
        ),
        LabelItem(
          key: remarkKey,
          label: "备注",
          maxTextLength: 1000,
          value: leadsInfo.remark,
          labelType: LabelType.TEXTAREA,
          onChanged: (text) {
            setState(() {
              leadsInfo.remark = text;
            });
          },
        ),
        CommonAttachment(
          key: picKey,
          picList: picList,
          picUrlList: picUrlList,
          onSelected: (values, images) {
            _attachmentImages = images;
            List<Map<String, dynamic>> picList = [];
            if (values.isEmpty) {
              leadsInfo.filesList = null;
            } else {
              for (int i = 0; i < values.length; i++) {
                Map<String, dynamic> fileMap = {
                  "fileUploadInfoId": values[i],
                  "url": null
                };
                picList.add(fileMap);
              }
              leadsInfo.filesList = picList;
            }
          },
        )
      ],
    );
  }

  Widget getCityLabel() {
    return Container(
      height: 45.px,
      padding: EdgeInsets.symmetric(horizontal: 15.px),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(
              color: WColors.border, // 边框颜色
              width: 0.5.px, // 边框宽度
            ),
          )),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          WText(
            "省市区",
            style: TextStyle(
                color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
          ),
          GestureDetector(
              onTap: () {
                _showCityPicker().then((res) {
                  if (res == null) {
                    return;
                  }
                  print(res);
                  leadsInfo.province = int.parse(res.provinceId);
                  leadsInfo.city = int.parse(res.cityId);
                  leadsInfo.county = int.parse(res.areaId);
                  areaStr = "${res.provinceName}${res.cityName}${res.areaName}";
                  setState(() {});
                });
              },
              child: SizedBox(
                height: 48.px,
                width: SizeUtils.screenW() - 140.px,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Text(
                      StringUtils.isEmpty(areaStr) ? "请选择" : areaStr,
                      style: TextStyle(
                        color: StringUtils.isEmpty(areaStr)
                            ? WColors.CCCCCCC
                            : WColors.subTextColor,
                        fontSize: WDimens.tsLabel,
                      ),
                    ),
                    SizedBox(
                      width: 5.px,
                    ),
                    Image.asset(
                      "images/ic_right.png",
                      color: WColors.CCCCCCC,
                      width: 12.px,
                    ),
                  ],
                ),
              ))
        ],
      ),
    );
  }

  Future _showCityPicker() async {
    return CityPickers.showCityPicker(
        height: 250.px,
        context: context,
        locationCode: leadsInfo.county.toString(),
        citiesData: Map<String, dynamic>.from(cityData["citiesData"]),
        provincesData: Map<String, String>.from(cityData["provincesData"]),
        cancelWidget: WText(
          "取消",
          style:
              TextStyle(fontSize: WDimens.tsLarge, color: WColors.subTextColor),
        ),
        confirmWidget: WText(
          "确定",
          style:
              TextStyle(fontSize: WDimens.tsLarge, color: WColors.primaryColor),
        ));
  }

  void filterTimeSlot(String dateStr) {
    filterTimeSlots = [];
    DateTime selectDate = DateTime.parse(dateStr);
    DateTime today = DateTime.now();
    if (DateUtils.isSameDay(selectDate, today)) {
      for (int i = 0; i < timeSlots!.length; i++) {
        String endTimeStr = timeSlots![i]["timeRange"].split("-").last.trim();
        String temp = "$dateStr $endTimeStr:00";
        DateTime givenDate = DateTime.parse(temp);
        if (givenDate.isAfter(today)) {
          filterTimeSlots?.add(timeSlots![i]);
        }
      }
    } else {
      filterTimeSlots = timeSlots;
    }
  }

  Widget _followUpList() {
    print("leadsFollowInfo.modelId: ${leadsFollowInfo.modelId}");

    return ListView(padding: EdgeInsets.zero, children: [
      LabelItem(
        label: "跟进方式",
        isMust: true,
        labelType: LabelType.DROW_DOWN,
        onSelected: (value) {
          setState(() {
            leadsFollowInfo.followMethod =
                value == null ? null : int.parse(value);
          });
        },
        dataList: WConstant.followUpWayList,
        value: leadsFollowInfo.followMethod.toString(),
      ),
      LabelItem(
        label: "跟进结果",
        isMust: true,
        labelType: LabelType.DROW_DOWN,
        onSelected: (value) {
          setState(() {
            if (value == null) {
              leadsFollowInfo.followResult = null;

              ///跟进结果置为空,需要清空数据
              ///1.意向级别 2.下次跟进时间 3.邀约试驾 4.预约试驾时间 5.战败原因 6.无效原因
              leadsFollowInfo.level = null;
              leadsFollowInfo.nextFollowTime = null;
              leadsFollowInfo.isAppointDrive = null;
              leadsFollowInfo.appointDriveTime = null;
              leadsFollowInfo.defeatReason = null;
              leadsFollowInfo.invalidReason = null;
              //remarkKey!.currentState?.refreshInput(leadsInfo.remark ?? "");
            } else {
              leadsFollowInfo.followResult = int.parse(value);

              ///跟进结果不为空
              if (leadsFollowInfo.followResult == 19101001) {
                ///1.跟进结果为继续, 需要清空数据
                ///a.战败原因 b.无效原因 c.意向级别
                leadsFollowInfo.defeatReason = null;
                leadsFollowInfo.invalidReason = null;
                //remarkKey!.currentState?.refreshInput(leadsInfo.remark ?? "");
              } else if (leadsFollowInfo.followResult == 19101002) {
                ///2.跟进结果为战败, 需要清空数据
                ///a.意向级别 b.下次跟进时间 c.邀约试驾 d.预约试驾时间 e.无效原因 f.战败原因
                leadsFollowInfo.level = null;
                leadsFollowInfo.nextFollowTime = null;
                leadsFollowInfo.isAppointDrive = null;
                leadsFollowInfo.appointDriveTime = null;
                leadsFollowInfo.invalidReason = null;
                leadsFollowInfo.defeatReason = null;
                //remarkKey!.currentState?.refreshInput(leadsInfo.remark ?? "");
              } else {
                ///3. 跟进结果为无效, 需要清空数据
                ///a.意向级别 b.下次跟进时间 c.邀约试驾 d.预约试驾时间 e.战败原因 f.无效原因
                leadsFollowInfo.level = null;
                leadsFollowInfo.nextFollowTime = null;
                leadsFollowInfo.isAppointDrive = null;
                leadsFollowInfo.appointDriveTime = null;
                leadsFollowInfo.defeatReason = null;
                leadsFollowInfo.invalidReason = null;
                //remarkKey!.currentState?.refreshInput(leadsInfo.remark ?? "");
              }
            }
          });
        },
        dataList: WConstant.followUpResultList,
        value: leadsFollowInfo.followResult.toString(),
      ),
      if (CommonReqUtils.exchangeCodeToName(
              CommonReqUtils.followUpResult, leadsFollowInfo.followResult) ==
          "战败")
        LabelItem(
          key: defeatReasonKey,
          label: "战败原因",
          isMust: true,
          labelType: LabelType.DROW_DOWN,
          onSelected: (value) {
            setState(() {
              leadsFollowInfo.defeatReason =
                  value == null ? null : int.parse(value);
            });
          },
          dataList: WConstant.defeatResultList,
          value: leadsFollowInfo.defeatReason.toString(),
        ),
      if (CommonReqUtils.exchangeCodeToName(
              CommonReqUtils.followUpResult, leadsFollowInfo.followResult) ==
          "无效")
        LabelItem(
          key: invalidReasonKey,
          label: "无效原因",
          isMust: true,
          labelType: LabelType.DROW_DOWN,
          onSelected: (value) {
            setState(() {
              leadsFollowInfo.invalidReason =
                  value == null ? null : int.parse(value);
            });
          },
          dataList: WConstant.invalidityReasonList,
          value: leadsFollowInfo.invalidReason.toString(),
        ),
      if (leadsFollowInfo.followResult == 19101001)
        LabelItem(
          label: "意向级别",
          isMust: true,
          isModel: true,
          labelType: LabelType.LIST,
          onSelected: (value) {
            setState(() {
              leadsFollowInfo.level = value == null ? null : int.parse(value);
              if (leadsFollowInfo.level != null) {
                dayLimit = leadsFollowRule
                    .where((rule) => rule.level == leadsFollowInfo.level)
                    .first
                    .intervalDays!;
                leadsFollowInfo.nextFollowTime = DateUtil.formatDate(
                    DateTime.now().add(Duration(days: dayLimit)),
                    format: DateFormats.y_mo_d);
                nextFollowTimeKey?.currentState
                    ?.refreshDate(leadsFollowInfo.nextFollowTime!);
              }
            });
          },
          dataList: WConstant.intentRangeList,
          value: leadsFollowInfo.level.toString(),
        ),
      LabelItem(
        labelType: LabelType.TEXTAREA,
        maxTextLength: 1000,
        isMust: true,
        label: "跟进记录",
        onChanged: (text) {
          setState(() {
            leadsFollowInfo.followRemark = text;
          });
        },
        value: leadsFollowInfo.followRemark,
      ),
      if (leadsFollowInfo.followResult == 19101001) getNextFollowTime(),
      // LabelItem(
      //   key: nextFollowTimeKey,
      //   isMust: true,
      //   labelType: LabelType.DATE,
      //   label: "下次跟进时间:",
      //   minDateTime: DateTime.now(),
      //   maxDateTime: DateTime.now().add(Duration(days: dayLimit)),
      //   onDateChanged: (text) {
      //     setState(() {
      //       leadsFollowInfo.nextFollowTime = text;
      //     });
      //   },
      //   selectedDate: leadsFollowInfo.nextFollowTime,
      // ),
      if (leadsFollowInfo.followResult == 19101001)
        LabelItem(
          label: "邀约到店/试驾",
          labelType: LabelType.LIST,
          onSelected: (value) {
            setState(() {
              leadsFollowInfo.isAppointDrive =
                  value == null ? null : int.parse(value);
              //leadsFollowInfo.modelId = null;
              leadsFollowInfo.appointDriveTime = null;
              leadsFollowInfo.appointDriveResourceId = null;
              leadsFollowInfo.appointDriveTimeShow = null;
            });
          },
          dataList: WConstant.appointTypeList,
          value: leadsFollowInfo.isAppointDrive.toString(),
        ),
      if (leadsFollowInfo.isAppointDrive == 10221002)
        LabelItem(
          label: "预约试驾车型",
          isMust: true,
          labelType: LabelType.DROW_DOWN,
          onSelected: (value) {
            setState(() {
              leadsFollowInfo.modelId = value;
            });
          },
          dataList: CommonReqUtils.getLabelListByKey(CommonReqUtils.carType),
          value: leadsFollowInfo.modelId.toString(),
        ),
      if (leadsFollowInfo.isAppointDrive != null)
        getAppointTime(leadsFollowInfo.isAppointDrive!),
      // LabelItem(
      //   key: appointDriveTimeKey,
      //   labelType: LabelType.DATE,
      //   label: "预约试驾日期",
      //   minDateTime: DateTime.now(),
      //   isMust: true,
      //   onDateChanged: (text) {
      //     setState(() {
      //       leadsFollowInfo.appointDriveTime = text;
      //       leadsFollowInfo.appointDriveTimeShow = null;
      //       filterTimeSlot(text);
      //     });
      //   },
      //   selectedDate: leadsFollowInfo.appointDriveTime,
      // ),
      if (leadsFollowInfo.isAppointDrive != null)
        LabelItem(
          key: appointDriveTimeShowKey,
          label:
              leadsFollowInfo.isAppointDrive == 10221001 ? "预约到店时间" : "预约试驾时间",
          isMust: true,
          labelType: LabelType.SELECT,
          value: leadsFollowInfo.appointDriveTimeShow,
          onTap: () {
            if (leadsFollowInfo.appointDriveTime == null) {
              Toast.toast("请先选择预约日期");
              return;
            }
            WPopupWindow.showBookTimeForClue(
                dataList: filterTimeSlots ?? [],
                context: context,
                leadsFollowInfo: leadsFollowInfo,
                onSelected: (info) {
                  leadsFollowInfo = info;
                  setState(() {});
                });
          },
        ),
      CommonAttachment(
        onSelected: (values, images) {
          List<Map<String, dynamic>> picList = [];
          if (values.isEmpty) {
            leadsFollowInfo.filesList = null;
          } else {
            for (int i = 0; i < values.length; i++) {
              Map<String, dynamic> fileMap = {
                "fileUploadInfoId": values[i],
                "url": null
              };
              picList.add(fileMap);
            }
            leadsFollowInfo.filesList = picList;
          }
        },
      )
    ]);
  }

  Widget getIntentDate() {
    return Container(
      height: 45.px,
      padding: EdgeInsets.symmetric(horizontal: 15.px),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(
              color: WColors.border, // 边框颜色
              width: 0.5.px, // 边框宽度
            ),
          )),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              WText(
                "意向购车日期",
                style: TextStyle(
                    color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
              ),
            ],
          ),
          GestureDetector(
              onTap: () {
                _showDatePickerForDate(
                    DateTime.now(),
                    null,
                    DateUtil.getDateTime(
                        leadsInfo.purchaseDate ?? ""))
                    .then((dateTime) {
                  if (dateTime != null && dateTime.isNotEmpty) {
                    var selectDate = dateTime[0];
                    var currentDate = DateUtil.formatDate(selectDate,
                        format: DateFormats.y_mo_d);
                    setState(() {
                      leadsInfo.purchaseDate = currentDate;
                    });
                  }
                });
              },
              child: SizedBox(
                height: 48.px,
                width: SizeUtils.screenW() - 140.px,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Text(
                      (leadsInfo.purchaseDate == null || leadsInfo.purchaseDate == "") ? "请选择" : leadsInfo.purchaseDate.toString(),
                      style: TextStyle(
                        color: (leadsInfo.purchaseDate == null || leadsInfo.purchaseDate == "")
                            ? WColors.CCCCCCC
                            : WColors.subTextColor,
                        fontSize: WDimens.tsLabel,
                      ),
                    ),
                    SizedBox(
                      width: 5.px,
                    ),
                    Image.asset(
                      "images/ic_right.png",
                      color: WColors.CCCCCCC,
                      width: 12.px,
                    ),
                  ],
                ),
              ))
        ],
      ),
    );
  }

  Widget getBirthday() {
    return Container(
      height: 45.px,
      padding: EdgeInsets.symmetric(horizontal: 15.px),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(
              color: WColors.border, // 边框颜色
              width: 0.5.px, // 边框宽度
            ),
          )),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              WText(
                "客户生日",
                style: TextStyle(
                    color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
              ),
            ],
          ),
          GestureDetector(
              onTap: () {
                _showDatePickerForDate(
                    DateTime(1970, 1, 1),
                    null,
                    DateUtil.getDateTime(
                        leadsInfo.birthday ?? ""))
                    .then((dateTime) {
                  if (dateTime != null && dateTime.isNotEmpty) {
                    var selectDate = dateTime[0];
                    var currentDate = DateUtil.formatDate(selectDate,
                        format: DateFormats.y_mo_d);
                    setState(() {
                      leadsInfo.birthday = currentDate;
                    });
                  }
                });
              },
              child: SizedBox(
                height: 48.px,
                width: SizeUtils.screenW() - 140.px,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Text(
                      (leadsInfo.birthday == null || leadsInfo.birthday == "") ? "请选择" : leadsInfo.birthday.toString(),
                      style: TextStyle(
                        color: (leadsInfo.birthday == null || leadsInfo.birthday == "")
                            ? WColors.CCCCCCC
                            : WColors.subTextColor,
                        fontSize: WDimens.tsLabel,
                      ),
                    ),
                    SizedBox(
                      width: 5.px,
                    ),
                    Image.asset(
                      "images/ic_right.png",
                      color: WColors.CCCCCCC,
                      width: 12.px,
                    ),
                  ],
                ),
              ))
        ],
      ),
    );
  }

  Widget getNextFollowTime() {
    return Container(
      height: 45.px,
      padding: EdgeInsets.symmetric(horizontal: 15.px),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(
              color: WColors.border, // 边框颜色
              width: 0.5.px, // 边框宽度
            ),
          )),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Offstage(
                offstage: false,
                child: WText(
                  "*",
                  style: TextStyle(
                      color: WColors.redMain, fontSize: WDimens.tsXXLarge),
                ),
              ),
              WText(
                "下次跟进时间",
                style: TextStyle(
                    color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
              ),
            ],
          ),
          GestureDetector(
              onTap: () {
                _showDatePickerForDate(
                        DateTime.now(),
                        DateTime.now().add(Duration(days: dayLimit)),
                        DateUtil.getDateTime(
                            leadsFollowInfo.nextFollowTime ?? ""))
                    .then((dateTime) {
                  if (dateTime != null && dateTime.isNotEmpty) {
                    var selectDate = dateTime[0];
                    var currentDate = DateUtil.formatDate(selectDate,
                        format: DateFormats.y_mo_d);
                    setState(() {
                      leadsFollowInfo.nextFollowTime = currentDate;
                    });
                  }
                });
              },
              child: SizedBox(
                height: 48.px,
                width: SizeUtils.screenW() - 140.px,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Text(
                      leadsFollowInfo.nextFollowTime ?? "请选择",
                      style: TextStyle(
                        color: leadsFollowInfo.nextFollowTime == null
                            ? WColors.CCCCCCC
                            : WColors.subTextColor,
                        fontSize: WDimens.tsLabel,
                      ),
                    ),
                    SizedBox(
                      width: 5.px,
                    ),
                    Image.asset(
                      "images/ic_right.png",
                      color: WColors.CCCCCCC,
                      width: 12.px,
                    ),
                  ],
                ),
              ))
        ],
      ),
    );
  }

  Widget getAppointTime(int type) {
    return Container(
      height: 45.px,
      padding: EdgeInsets.symmetric(horizontal: 15.px),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(
              color: WColors.border, // 边框颜色
              width: 0.5.px, // 边框宽度
            ),
          )),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Offstage(
                offstage: false,
                child: WText(
                  "*",
                  style: TextStyle(
                      color: WColors.redMain, fontSize: WDimens.tsXXLarge),
                ),
              ),
              WText(
                type == 10221001 ? "预约到店日期" : "预约试驾日期",
                style: TextStyle(
                    color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
              ),
            ],
          ),
          GestureDetector(
              onTap: () {
                _showDatePickerForDate(
                        DateTime.now(),
                        DateTime(2050, 12, 31),
                        DateUtil.getDateTime(
                            leadsFollowInfo.appointDriveTime ?? ""))
                    .then((dateTime) {
                  if (dateTime != null && dateTime.isNotEmpty) {
                    var selectDate = dateTime[0];
                    var currentDate = DateUtil.formatDate(selectDate,
                        format: DateFormats.y_mo_d);
                    setState(() {
                      leadsFollowInfo.appointDriveTime = currentDate;
                      leadsFollowInfo.appointDriveTimeShow = null;
                      filterTimeSlot(currentDate);
                    });
                  }
                });
              },
              child: SizedBox(
                height: 48.px,
                width: SizeUtils.screenW() - 140.px,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Text(
                      leadsFollowInfo.appointDriveTime ?? "请选择",
                      style: TextStyle(
                        color: leadsFollowInfo.appointDriveTime == null
                            ? WColors.CCCCCCC
                            : WColors.subTextColor,
                        fontSize: WDimens.tsLabel,
                      ),
                    ),
                    SizedBox(
                      width: 5.px,
                    ),
                    Image.asset(
                      "images/ic_right.png",
                      color: WColors.CCCCCCC,
                      width: 12.px,
                    ),
                  ],
                ),
              ))
        ],
      ),
    );
  }

  Future _showDatePickerForDate(minDateTime, maxDateTime, selectDate) async {
    return CommonDate.showPicker(
        context: context,
        firstDate: minDateTime ?? DateTime(2020, 1, 1),
        lastDate: maxDateTime ?? DateTime(2030, 12, 31),
        currentDate: selectDate,
        value: [selectDate ?? DateTime.now()]);
  }
}
